package com.chaos.gateway.helper;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chaos.framework.model.constant.SecurityConstants;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.model.exception.BusinessException;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import java.text.ParseException;

@Slf4j
public class JwtTokenHelper {

    public static JSONObject getTokenMap(String accessToken) {
        try {
            String token = StrUtil.replaceIgnoreCase(accessToken, SecurityConstants.JWT_PREFIX, Strings.EMPTY);
            String payload = StrUtil.toString(JWSObject.parse(token).getPayload());
            return JSONUtil.parseObj(payload);
        } catch (ParseException e) {
            log.error("JwtTokenUtils getTokenMap ParseException");
            throw new BusinessException(ResultEnum.TOKEN_INVALID_OR_EXPIRED);
        }
    }


}
